import * as introduceApi from '@/api/introduce'
import {
  getUnread
} from '@/api/inform'

import {
  getStorage
} from '@/utils/storage'
const appInstance = getApp()
Page({
  data: {
    isRead: true,
    messageNumber: "",
    teamImg: '', //团队照片
    currentIndex: 0, // 当前显示的图片索引,
    article: [], //所有推文
    articleDetail: [] //推文详细信息
  },

  async onLoad() {

  },

  async onShow() {
    // 请求通知消息数量
    this.checkDot()
    // 请求推文
    this.reqTweet()
    // 请求团队
    const teamRes = await introduceApi.getTeam();
    // console.log(teamRes);
    this.setData({
      teamImg: teamRes.data.pic[0],
    })
  },



  // 请求推文信息
  async reqTweet() {
    const {
      data
    } = await introduceApi.getTweet()
    //console.log(data)
    this.setData({
      article: data,
      articleDetail: [] // 清空原本内容
    })


    // 请求每个推文具体信息
    this.data.article.map(async item => {
      const res = await introduceApi.getTweetDetail(item.id)
      //console.log(res.data)
      this.setData({
        articleDetail: [...this.data.articleDetail, res.data]
      });
    });
  },

  async Unread() {
    try {
      const {
        data
      } = await getUnread();
      //console.log(data);

      // 更新全局数据和组件状态
      appInstance.globalData.isRead = data === 0;
      this.setData({
        isRead: appInstance.globalData.isRead,
        messageNumber: data,
      });
    } catch (error) {
      console.error('Failed to fetch unread messages:', error);
    }
  },
  async checkDot() {
    clearInterval(appInstance.globalData.pollingInterval)

    const that = this;
    if (getStorage("token")) {
      this.Unread()
      // 设置定时器
      appInstance.globalData.pollingInterval = setInterval(async () => {
        that.Unread()
      }, 5000);
    }
  },
})